﻿using Aspose.Cells;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace MergePlus
{

    public class InvoiceData
    {
        public string ReleaseNo { set; get; }
        public string Container { set; get; }
        public string FirstType { set; get; }
        public string SecondType { set; get; }
        public string Qty { set; get; }
        public string Power { set; get; }
    }

    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        public string path { set; get; } = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

        /// <summary>
        /// 获取文件夹下所有文件
        /// </summary>
        /// <param name="folderName">文件夹名称</param>
        /// <returns></returns>
        private FileInfo[] LoadFiles(string folderName)
        {
            //获取当前路径
            DirectoryInfo root = new DirectoryInfo(path + @"/" + folderName + @"/");
            //获取EfolderName目录下所有文件
            return root.GetFiles();
        }


        private void Create_Click(object sender, RoutedEventArgs e)
        {
            var files = this.LoadFiles("合并Excel_第一列和第八列");
            if (files.Length == 0) { MessageBox.Show("'合并Excel_第一列和第八列'文件夹中没有找到文件！"); return; }
            var releaseNoList = files.Select(t => t.Name.Trim()).Distinct().ToList();

            var baseFile = this.LoadFiles("合并Excel_物流数据");
            if (baseFile.Length == 0) { MessageBox.Show("'合并Excel_物流数据'文件夹中没有找到文件！"); return; }
            Aspose.Cells.Workbook baseWorkbook = new Aspose.Cells.Workbook(baseFile[0].FullName);
            Worksheet baseWorksheet = baseWorkbook.Worksheets[0];

            var releaseNoInx = -1; var containerInx = -1; var firstTypeInx = -1; var secondTypeInx = -1; var qtyInx = -1; var powerInx = -1;

            for (int i = 0; i < baseWorksheet.Cells.MaxDataColumn; i++)//baseWorksheet.Cells.Columns.Count 不一定准确，所以用MaxDataColumn
            {
                var name = baseWorksheet.Cells[0, i].Value;
                if (name == null) continue;
                switch (name.ToString().Trim())
                {
                    case "DN": case "ReleaseNo": releaseNoInx = i; break;
                    case "Container": containerInx = i; break;
                    case "Type":
                        if (firstTypeInx == -1) firstTypeInx = i;
                        if (firstTypeInx > -1) secondTypeInx = i;
                        break;
                    case "Qty(PC)": qtyInx = i; break;
                    case "Power(w/pc)": powerInx = i; break;
                    default: break;
                }
                if (releaseNoInx != -1 && containerInx != -1 && firstTypeInx != -1 && secondTypeInx != -1 && qtyInx != -1 && powerInx != -1) { break; }

            }

            if (releaseNoInx == -1) { MessageBox.Show("找不到DN列！"); return; }
            if (containerInx == -1) { MessageBox.Show("找不到Container列！"); return; }
            if (firstTypeInx == -1) { MessageBox.Show("找不到Type列！"); return; }
            if (secondTypeInx == -1) { MessageBox.Show("只找到一个Type列！"); return; }
            if (qtyInx == -1) { MessageBox.Show("找不到Qty(PC)列！"); return; }
            if (powerInx == -1) { MessageBox.Show("找不到Power(w/pc)列！"); return; }
            var dict = new Dictionary<string, List<InvoiceData>>();

            Parallel.ForEach(files, file =>
            {
                var fileName = file.Name.Trim();
                if (fileName.StartsWith("~")) return;
                var releaseNo = "";
                for (int row = 1; row < baseWorksheet.Cells.Rows.Count; row++)
                {
                    var newReleaseNo = baseWorksheet.Cells[row, releaseNoInx].Value;

                    if (newReleaseNo != null && newReleaseNo.ToString().Trim() == fileName)
                    {
                        releaseNo = newReleaseNo.ToString().Trim();
                    }
                    else if (releaseNo == fileName && newReleaseNo == null)
                    {

                    }
                    else
                    {
                        continue;
                    }



                    if (newReleaseNo != null && string.IsNullOrEmpty(newReleaseNo.ToString().Trim()))
                    {
                        releaseNo = newReleaseNo.ToString().Trim();
                        if (!dict.ContainsKey(releaseNo))
                        {
                            dict.Add(releaseNo, new List<InvoiceData>());
                        }
                    }

                    var container = baseWorksheet.Cells[row, containerInx].Value;
                    var type = baseWorksheet.Cells[row, firstTypeInx].Value;
                    var qty = baseWorksheet.Cells[row, qtyInx].Value;
                    var power = baseWorksheet.Cells[row, powerInx].Value;
                    if (container == null || type == null || qty == null || power == null) continue;
                    if (container.ToString().Trim() == "Container" && type.ToString().Trim() == "Type" && qty.ToString().Trim() == "Qty(PC)" && power.ToString().Trim() == "Power(w/pc)") continue;
                    dict[releaseNo].Add(new InvoiceData() { ReleaseNo = releaseNo, Container = container.ToString().Trim(), FirstType = type.ToString().Trim(), SecondType = "", Qty = qty.ToString().Trim(), Power = power.ToString().Trim() });
                }










                var workbook = new Workbook(file.FullName);
                var worksheet = workbook.Worksheets[0];
                var rowInfo = worksheet.Cells[0, 0];
                if (rowInfo == null) return;
                if (rowInfo.Value == null) return;
                if (string.IsNullOrEmpty(rowInfo.Value.ToString().Trim())) return;


            });

            for (int row = 0; row < baseWorksheet.Cells.Rows.Count; row++)
            {
                var newReleaseNo = baseWorksheet.Cells[row, releaseNoInx].Value;
                if (newReleaseNo != null && string.IsNullOrEmpty(newReleaseNo.ToString().Trim()))
                {
                    releaseNo = newReleaseNo.ToString().Trim();
                }
                //if (!dict.ContainsKey(releaseNo))
                //{
                //    dict.Add(releaseNo, new List<InvoiceData>());
                //}

                foreach (var releaseNoItem in releaseNoList)
                {
                    if (releaseNoList.Contains(releaseNo))
                    {
                        var containerList = new List<int>();
                        var typeList = new List<int>();
                        var qtyList = new List<int>();
                        var powerList = new List<int>();
                        for (int i = 0; i < baseWorksheet.Cells.MaxDataRow; i++)
                        {
                            var container = baseWorksheet.Cells[i, containerInx].Value;
                            var type = baseWorksheet.Cells[i, firstTypeInx].Value;
                            var qty = baseWorksheet.Cells[i, qtyInx].Value;
                            var power = baseWorksheet.Cells[i, powerInx].Value;
                            if (container == null || type == null || qty == null || power == null) continue;
                            if (releaseNo == rowInfo.Value.ToString().Trim() && container.ToString().Trim() == "Container" && type.ToString().Trim() == "Type" && qty.ToString().Trim() == "Qty(PC)" && power.ToString().Trim() == "Power(w/pc)") continue;
                            containerList.Add(i);
                            typeList.Add(i);
                            qtyList.Add(i);
                            powerList.Add(i);
                        }
                        dict.Add(releaseNo, new List<string>() { containerList.Count, typeList.Count, qtyList.Count, powerList.Count });
                    }
                }

                if (newReleaseNo == null)
                {
                    dict.Where(t => t.Key == releaseNo).First().Value.Add(row);
                }
                else
                {
                    releaseNo = newReleaseNo.ToString().Trim();
                }
                if (!dict.ContainsKey(newReleaseNo.ToString().Trim()))
                {
                    dict.Add(releaseNo.ToString().Trim(), new List<string>() { "Container", "Type", "Qty(PC)", "Power(w/pc)" });
                }



            }

            var result = new List<string>();
            result.Add("DN,Container,Type,Qty(PC),Power(w/pc)");
            foreach (var releaseNo in releaseNoList)
            {
                var containerList = dict[releaseNo][0];
                var typeList = dict[releaseNo][1];
                var qtyList = dict[releaseNo][2];
                var powerList = dict[releaseNo][3];
                for (int i = 0; i < containerList; i++)
                {
                    var container = baseWorksheet.Cells[i + 1, containerInx].Value;
                    var type = baseWorksheet.Cells[i + 1, firstTypeInx].Value;
                    var qty = baseWorksheet.Cells[i + 1, qtyInx].Value;
                    var power = baseWorksheet.Cells[i + 1, powerInx].Value;
                    result.Add(releaseNo + "," + container + "," + type + "," + qty + "," + power);
                }
            }

            var saveFileDialog = new Microsoft.Win32.SaveFileDialog();
            saveFileDialog.Filter = "Excel 文件|*.xlsx";
            saveFileDialog.FileName = "合并结果.xlsx";
            if (saveFileDialog.ShowDialog() == true)
            {
                var workbook = new Workbook();
                var worksheet = workbook.Worksheets[0];
                for (int i = 0; i < result.Count; i++)
                {
                    worksheet.Cells[i, 0].Value = result[i];
                }
                workbook.Save(saveFileDialog.FileName);
            }
            MessageBox.Show("合并完成！");

        }
    }
}
